<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;

class FeedHistory extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function read(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedhistory:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'optTime', 'trim');
		$order = $request->param('order', 'desc', 'trim');

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 2 ] );
		 
		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['userid', '=',  $userId ] );
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['bazaarId', '=',  $bazaarId ] );
		}

 		$optLevel = $request->param('optLevel', '', 'trim');
		if($optLevel) {
			array_push( $where, ['optLevel', '=',  $optLevel ] );
		}

		$optContent = $request->param('optContent', '', 'trim');
		if($optContent) {
			array_push( $where, ['optContent', '=',  $optContent ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			array_push( $where, ['optTime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, true) ] );
		} else {
			array_push( $where, ['optTime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true) ] );
		}
    //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $where, ['userid', 'in',  $authaccount ] );
			}
		}
		$query = Db::name('cfg_optlog')->where($where)->order($sort, $order)->paginate($limit);
		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $query->items(),
			'expand' => Expand::getList($request->sessInfo, 2),
			'bazaar' => Bazaar::getList($request->sessInfo, 2) ];
	}

	/**
	 * 清除三个月之前日志
	 *
	 * @return
	 */
	public function clearLog(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedhistory:clear')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$beginTime = microtime(true);
		$count = Db::table('cfg_optlog')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)
		  ->where('optTime', '<=', time() - ( 86400 * 90 ))->count();
		Db::table('cfg_optlog')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)
		  ->where('optTime', '<=', time() - ( 86400 * 90 ))->delete();
		$endTime = microtime(true);
		$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
		$request->sessInfo['username'], round($endTime - $beginTime, 3), '历史操作记录', '清除三个月之前日志!', 0, null);
		return json(['code'=> 0, 'msg'=> '成功删除'.$count.'条日志!']);
	}

	/**
	 * 同步选中账户
	 *
	 * @return
	 */
	public function synchronous(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedhistory:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if(!$userId) {
			return json(['code'=> 403, 'msg'=> '请选择同步账户!']);
		}

		$beginTime = microtime(true);
		$expand = Expand::getUserInfo($request->sessInfo, $userId, 2);
		if($expand === false) {
			return json(['code'=> 403, 'msg'=> '账户不存在!']);
		}

    // 推广单元历史操作记录
	  $result = doPostRequest('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
			'header'=> [ 'username'=> $expand->username, 'password'=> $expand->password, 'token'=> $expand->token ],
			'body'=>[
				'startDate' => date('Y-m-d'),
				'endDate' => date("Y-m-d", strtotime("+1 day")),
			  'recordType' => 2,
				'optTypes'=> null,
				"optLevel"=> 1
			]
		]));

		if(empty($result)) {
			return json(['code'=> 403, 'msg'=> '账户同步失败!']);
		}

		$record = json_decode ($result);
		if(!isset($record->header->desc)) {
			return json(['code'=> 403, 'msg'=> '账户同步失败!']);
		}

		if( $record->header->desc == 'failure' ){
			return json(['code'=> 403, 'msg'=> $record->header->failures[0]->code . ',' . $record->header->failures[0]->message ]);
		}

		if( isset( $record->body->data[0] ) ) {
			foreach ($record->body->data as $value ) {
				$value->optContent = isset($value->optContent) ? $value->optContent : 0;
				if($value->optContent) {
					$value->unitId = isset($value->unitId) ? $value->unitId : 0;
					$value->planId = isset($value->planId) ? $value->planId : 0;
					$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
					$md5 = md5($request->sessInfo['companyId'].'2'.json_encode($value, JSON_FORCE_OBJECT));
					$query = Db::table('cfg_optlog')->where('md5', $md5)->cache(86400)->value('id');
					if(empty($query)) {
						 Db::table('cfg_optlog')->insert(['companyId'=> $request->sessInfo['companyId'], 'userType' => 2, 'userId'=> $value->userId, 'bazaarId' => $expand->bazaarId, 'planId'=> $value->planId, 'unitId'=> $value->unitId,
							 'optTime'=> $value->optTime, 'optContent'=> $value->optContent, 'optType'=> $value->optType, 'optLevel'=> $value->optLevel,
								 'oldValue'=>(string)$value->oldValue, 'newValue'=>(string)$value->newValue, 'optObj'=>$value->optObj, 'md5'=> $md5]);
					}
				}
			}
		}

    // 推广计划历史操作记录
	  $result = doPostRequest('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
			'header'=> [ 'username'=> $expand->username, 'password'=> $expand->password, 'token'=> $expand->token ],
			'body'=>[
				'startDate' => date('Y-m-d'),
				'endDate' => date("Y-m-d", strtotime("+1 day")),
				'optTypes'=> null,
			  'recordType' => 2,
				"optLevel"=> 2
			]
		]));
		if( $result ) {
			$record = json_decode ($result);
			if( isset( $record->body->data[0] ) ) {
				foreach ($record->body->data as $value ) {
					$value->optContent = isset($value->optContent) ? $value->optContent : 0;
					if($value->optContent) {
						$value->unitId = isset($value->unitId) ? $value->unitId : 0;
						$value->planId = isset($value->planId) ? $value->planId : 0;
				  	$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
						$md5 = md5($request->sessInfo['companyId'].'2'.json_encode($value, JSON_FORCE_OBJECT));
						$query = Db::table('cfg_optlog')->where('md5', $md5)->cache(86400)->value('id');
						if(empty($query)) {
							 Db::table('cfg_optlog')->insert(['companyId'=> $request->sessInfo['companyId'], 'userType' => 2, 'userId'=> $value->userId, 'bazaarId' => $expand->bazaarId, 'planId'=> $value->planId, 'unitId'=> $value->unitId,
								 'optTime'=> $value->optTime, 'optContent'=> $value->optContent, 'optType'=> $value->optType, 'optLevel'=> $value->optLevel,
									 'oldValue'=>(string)$value->oldValue, 'newValue'=>(string)$value->newValue, 'optObj'=>$value->optObj, 'md5'=> $md5]);
						}
					}
			  }
			}
		}

    // 帐户历史操作记录
	  $result = doPostRequest('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
			'header'=> [ 'username'=> $expand->username, 'password'=> $expand->password, 'token'=> $expand->token ],
			'body'=>[
				'startDate' => date('Y-m-d'),
				'endDate' => date("Y-m-d", strtotime("+1 day")),
				'optTypes'=> null,
			  'recordType' => 2,
				"optLevel"=> 3
			]
		]));
		if( $result ) {
			$record = json_decode ($result);
			if( isset( $record->body->data[0] ) ) {
				foreach ($record->body->data as $value ) {
					$value->optContent = isset($value->optContent) ? $value->optContent : 0;
					if($value->optContent) {
						$value->unitId = isset($value->unitId) ? $value->unitId : 0;
						$value->planId = isset($value->planId) ? $value->planId : 0;
				  	$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
						$md5 = md5($request->sessInfo['companyId'].'2'.json_encode($value, JSON_FORCE_OBJECT));
						$query = Db::table('cfg_optlog')->where('md5', $md5)->cache(86400)->value('id');
						if(empty($query)) {
							 Db::table('cfg_optlog')->insert(['companyId'=> $request->sessInfo['companyId'], 'userType' => 2, 'userId'=> $value->userId, 'bazaarId' => $expand->bazaarId, 'planId'=> $value->planId, 'unitId'=> $value->unitId,
								 'optTime'=> $value->optTime, 'optContent'=> $value->optContent, 'optType'=> $value->optType, 'optLevel'=> $value->optLevel,
									 'oldValue'=>(string)$value->oldValue, 'newValue'=>(string)$value->newValue, 'optObj'=>$value->optObj, 'md5'=> $md5]);
						}
					}
			  }
			}
		}

    // 创意历史操作记录
	  $result = doPostRequest('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
			'header'=> [ 'username'=> $expand->username, 'password'=> $expand->password, 'token'=> $expand->token ],
			'body'=>[
				'startDate' => date('Y-m-d'),
				'endDate' => date("Y-m-d", strtotime("+1 day")),
				'optTypes'=> null,
				'recordType' => 2,
				"optLevel"=> 4
			]
		]));
		if( $result ) {
			$record = json_decode ($result);
			if( isset( $record->body->data[0] ) ) {
				foreach ($record->body->data as $value ) {
					$value->optContent = isset($value->optContent) ? $value->optContent : 0;
					if($value->optContent) {
						$value->unitId = isset($value->unitId) ? $value->unitId : 0;
						$value->planId = isset($value->planId) ? $value->planId : 0;
				  	$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
						$md5 = md5($request->sessInfo['companyId'].'2'.json_encode($value, JSON_FORCE_OBJECT));
						$query = Db::table('cfg_optlog')->where('md5', $md5)->cache(86400)->value('id');
						if(empty($query)) {
							 Db::table('cfg_optlog')->insert(['companyId'=> $request->sessInfo['companyId'], 'userType' => 2, 'userId'=> $value->userId, 'bazaarId' => $expand->bazaarId, 'planId'=> $value->planId, 'unitId'=> $value->unitId,
								 'optTime'=> $value->optTime, 'optContent'=> $value->optContent, 'optType'=> $value->optType, 'optLevel'=> $value->optLevel,
									 'oldValue'=>(string)$value->oldValue, 'newValue'=>(string)$value->newValue, 'optObj'=>$value->optObj, 'md5'=> $md5]);
						}
					}
			  }
			}
		}

    // 关键词历史操作记录
	  $result = doPostRequest('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
			'header'=> [ 'username'=> $expand->username, 'password'=> $expand->password, 'token'=> $expand->token ],
			'body'=>[
				'startDate' => date('Y-m-d'),
				'endDate' => date("Y-m-d", strtotime("+1 day")),
				'optTypes'=> null,
			  'recordType' => 2,
				"optLevel"=> 5
			]
		]));
		if( $result ) {
			$record = json_decode ($result);
			if( isset( $record->body->data[0] ) ) {
				foreach ($record->body->data as $value ) {
					$value->optContent = isset($value->optContent) ? $value->optContent : 0;
					if($value->optContent) {
						$value->unitId = isset($value->unitId) ? $value->unitId : 0;
						$value->planId = isset($value->planId) ? $value->planId : 0;
				  	$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
						$md5 = md5($request->sessInfo['companyId'].'2'.json_encode($value, JSON_FORCE_OBJECT));
						$query = Db::table('cfg_optlog')->where('md5', $md5)->cache(86400)->value('id');
						if(empty($query)) {
							 Db::table('cfg_optlog')->insert(['companyId'=> $request->sessInfo['companyId'], 'userType' => 2, 'userId'=> $value->userId, 'bazaarId' => $expand->bazaarId, 'planId'=> $value->planId, 'unitId'=> $value->unitId,
								 'optTime'=> $value->optTime, 'optContent'=> $value->optContent, 'optType'=> $value->optType, 'optLevel'=> $value->optLevel,
									 'oldValue'=>(string)$value->oldValue, 'newValue'=>(string)$value->newValue, 'optObj'=>$value->optObj, 'md5'=> $md5]);
						}
					}
			  }
			}
		}

		$endTime = microtime(true);
		$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
		$request->sessInfo['username'], round($endTime - $beginTime, 3), '历史操作记录', '同步历史操作记录!', 0, null);
		return json(['code'=> 0, 'msg'=> '数据同步成功!']);
	}


}
